package com.cgsd.heyu.ui.task;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.text.Html;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.android.library.adapter.OnViewHelper;
import com.android.library.adapter.ViewHelper;
import com.android.library.image.GlideUtil;
import com.cgsd.heyu.R;
import com.cgsd.heyu.api.ApiService;
import com.cgsd.heyu.http.BaseResponse;
import com.cgsd.heyu.http.BaseRxSubscribe;
import com.cgsd.heyu.http.ErrorMessage;
import com.cgsd.heyu.http.RetrofitServiceManagerPhp;
import com.cgsd.heyu.http.RxjavaHelper;
import com.cgsd.heyu.presenter.BasePresenter;
import com.cgsd.heyu.ui.BaseActivity;
import com.cgsd.heyu.ui.task.adapter.PublishDetailAdapter;
import com.cgsd.heyu.ui.task.vo.PublishDetailVo;
import com.cgsd.heyu.utils.ImagePreviewActivity;
import com.cgsd.heyu.utils.RequestParams;
import com.cgsd.heyu.utils.StatusBarUtil;
import com.cgsd.heyu.widgets.dialog.WrapperDialog;
import com.cgsd.heyu.widgets.refresh.DensityUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.util.ArrayList;

import okhttp3.RequestBody;

/**
 * Author：sky on 2021/3/28 13:17.
 * Email：xcode126@126.com
 * Desc：
 */
public class PublishDetailActivity_v2 extends BaseActivity<BasePresenter> {

    private int tid;
    private RecyclerView mRecyclerView;
    private PublishDetailAdapter detailAdapter;

    public static Intent getIntent(Context context, int tid) {
        return new Intent(context, PublishDetailActivity_v2.class).putExtra("tid", tid);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_publish_detail_v2;
    }

    @Override
    protected void setStatusBar() {
        StatusBarUtil.fullBar(this);
    }

    @Override
    protected void initView() {
        tid = getIntent().getIntExtra("tid", 0);
        mRecyclerView = findViewById(R.id.mRecyclerView);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        detailAdapter = new PublishDetailAdapter();
        mRecyclerView.setAdapter(detailAdapter);
        detailAdapter.setHeaderAndEmpty(true);
        detailAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                PublishDetailVo.DostepBean item = detailAdapter.getItem(position);
                ArrayList<String> list = new ArrayList<>();
                list.add(item.backiimage);
                startActivity(ImagePreviewActivity.getIntent(PublishDetailActivity_v2.this, list, 0));
            }
        });
    }

    @Override
    protected void initData() {
        getPublishDetail();
    }

    /**
     * get Task list
     */
    public void getPublishDetail() {
        showLoading();
        RequestBody requestBody = new RequestParams()
                .put("page", page)//392 10001146
                .put("tid", tid)//分类ID,1为我的任务,2为我的发布,默认1
//                .putUid()
                .get();
        RetrofitServiceManagerPhp.getInstance().creat(ApiService.class)
                .getPublishDetail(requestBody)
                .compose(RxjavaHelper.observeOnMainThread())
                .subscribe(new BaseRxSubscribe<BaseResponse<PublishDetailVo>>() {
                    @Override
                    public void onSuccess(BaseResponse<PublishDetailVo> baseResponse) {
                        processPublishDetail(baseResponse.getBizBody());
                        loadSuccess();
                    }

                    @Override
                    public void onError(ErrorMessage error) {
                        setErrorMessage(error);
                        loadSuccess();
                    }
                });
    }

    /**
     * process publish detail
     *
     * @param detailVo
     */
    private void processPublishDetail(PublishDetailVo detailVo) {
        if (detailAdapter.getHeaderLayoutCount() > 0) {//先移除多余头部
            detailAdapter.removeAllHeaderView();
            detailAdapter.notifyDataSetChanged();
        }
        if (detailAdapter.getFooterLayoutCount() > 0) {//先移除多余尾部
            detailAdapter.removeAllFooterView();
            detailAdapter.notifyDataSetChanged();
        }
        if (detailVo.dostep != null && detailVo.dostep.size() > 0) {
            detailAdapter.setNewData(detailVo.dostep);
            detailAdapter.setFooterView(getFootView());//尾部审核按钮根据完成数据设置
        } else {
            detailAdapter.getData().clear();
            detailAdapter.setEmptyView(getEmptyView());
            detailAdapter.notifyDataSetChanged();
        }
        detailAdapter.setHeaderView(getHeaderView(detailVo.info, detailVo.replyer));
    }

    /**
     * get header view
     *
     * @param info
     * @param replyerBean
     * @return
     */
    private View getHeaderView(PublishDetailVo.InfoBean info, PublishDetailVo.ReplyerBean replyerBean) {
        return getHelperView(mRecyclerView, R.layout.header_publish_detail, new OnViewHelper() {
            @Override
            public void help(ViewHelper helper) {
                if (info != null) {
                    GlideUtil.loadRemoteImage(PublishDetailActivity_v2.this, info.gender, helper.getView(R.id.iv_bg));
                    helper.setText(R.id.tv_task_title, info.title);
                    helper.setText(R.id.tv_amount, info.price);
                    helper.setText(R.id.tv_commit, String.format("%1$s%2$s%3$s", getString(R.string.a_commit_), info.finish, getString(R.string.a_unit_hour)));
                    helper.setText(R.id.tv_complete, Html.fromHtml(String.format("%1$s<font color='#E94E4E'>%2$s</font>", getString(R.string.a_complete), info.tnum)));
                    helper.setText(R.id.tv_last, Html.fromHtml(String.format("%1$s<font color='#E94E4E'>%2$s</font>", getString(R.string.a_last), info.lastnum)));
                }
                helper.setVisible(R.id.ll_compete_detail, replyerBean != null);
                if (replyerBean != null) {
                    GlideUtil.loadRemoteImage(PublishDetailActivity_v2.this, replyerBean.imgurl, helper.getView(R.id.iv_header));
                    helper.setText(R.id.tv_nick, replyerBean.nick_name);
                    helper.setText(R.id.tv_commit_time, String.format("%1$s%2$s", getString(R.string.a_commit_time_), replyerBean.updatetime));
                    helper.setText(R.id.tv_check_status, Html.fromHtml(String.format("%1$s<font color='#33B9CC'>%2$s</font>", getString(R.string.a_check_status_), replyerBean.statetext)));
                }
                setBtnState(helper);
                helper.setOnClickListener(view -> {
                    switch (view.getId()) {
                        case R.id.tv_pause:
                            pauseStopTask(true);
                            break;
                        case R.id.tv_end:
                            pauseStopTask(false);
                            break;
                        case R.id.tv_publish:
                            startActivity(PublishTaskActivity.getIntent(PublishDetailActivity_v2.this, tid));
                            finish();
                            break;
                    }
                }, R.id.tv_end, R.id.tv_pause, R.id.tv_publish);
            }

            /**
             * 2020-4-2更改前
             * 状态值:0=草稿,1=待支付,2=上线,3=下线,4=暂停,5=完结,6=删除
             * 保存草稿或者支付未成功都是草稿状态，草稿状态可以编辑\发布，发布会再去支付。
             * 上线，可以暂停和中止，中止为完结
             * 暂停可以编辑再发布，如编辑数量补差支付
             * 删除系统状态，发布者不显示
             */
            /**
             * 2020-4-2更改后
             * 状态值:0=草稿,1=待支付,2=上线,3=下线,4=暂停,5=完结,6=删除
             * 0，1保存草稿或者支付未成功都是草稿状态，草稿状态可以编辑\发布，发布会再去支付。
             * 2.上线，可以暂停
             * 4.暂停可以编辑再发布和中止，如编辑数量补差支付，中止既为完结
             * 删除系统状态，发布者不显示
             */
            private void setBtnState(ViewHelper helper) {
                setBtnHide(helper);//隐藏所有按钮
                if (!TextUtils.isEmpty(info.state)) {
                    switch (info.state) {
                        case "0"://草稿
                        case "1"://待支付
                            helper.setViewVisible(R.id.tv_publish);//显示编辑并发布按钮
                            break;
                        case "2"://上线
                            helper.setViewVisible(R.id.tv_pause);//暂停
                            break;
                        case "4"://暂停
                            helper.setViewVisible(R.id.tv_publish);//显示编辑并发布按钮
                            helper.setViewVisible(R.id.tv_end);
                            break;
                        default:
                            setBtnHide(helper);
                    }
                }
            }

            /**
             * 设置左右按钮隐藏
             * @param helper
             */
            private void setBtnHide(ViewHelper helper) {
                helper.setViewGone(R.id.tv_publish);
                helper.setViewGone(R.id.tv_pause);
                helper.setViewGone(R.id.tv_end);
            }
        });
    }

    /**
     * get empty view
     *
     * @return
     */
    private View getEmptyView() {
        return getHelperView(mRecyclerView, R.layout.common_empty, new OnViewHelper() {
            @Override
            public void help(ViewHelper helper) {
                helper.setText(R.id.tv_content, "暂未有完成步骤");
            }
        });
    }

    /**
     * get empty view
     *
     * @return
     */
    private View getFootView() {
        return getHelperView(mRecyclerView, R.layout.foot_pulish_detail, new OnViewHelper() {
            @Override
            public void help(ViewHelper helper) {
                helper.setOnClickListener(view -> {
                    switch (view.getId()) {
                        case R.id.tv_no:
                            noPassDialog();
                            break;
                        case R.id.tv_yes:
                            checkTask("");
                            break;
                    }
                }, R.id.tv_no, R.id.tv_yes);
            }
        });
    }

    /**
     * pause Stop Task
     *
     * @param isPause 1:暂停,2:终止
     */
    private void pauseStopTask(boolean isPause) {
        showCommonSubmitDialog();
        RequestBody requestBody = new RequestParams().put("act", isPause ? 1 : 2)
                .put("tid", tid)
                .putUid().get();
        RetrofitServiceManagerPhp.getInstance().creat(ApiService.class)
                .pauseStopTask(requestBody)
                .compose(RxjavaHelper.observeOnMainThread())
                .subscribe(new BaseRxSubscribe<BaseResponse<String>>() {
                    @Override
                    public void onSuccess(BaseResponse<String> baseResponse) {
                        dismissCommonSubmitDialog();
                        getPublishDetail();
                    }

                    @Override
                    public void onError(ErrorMessage error) {
                        setErrorMessage(error);
                    }
                });
    }

    /**
     * pause Stop Task
     *
     * @param reason 1:通过,2:驳回(传reason)
     */
    private void checkTask(String reason) {
        showCommonSubmitDialog();
        int act = TextUtils.isEmpty(reason) ? 2 : 1;
        RequestBody requestBody = new RequestParams()
                .put("act", act)
                .put("tid", tid)
                .putWithoutEmpty("reason", reason)
                .putUid().get();
        RetrofitServiceManagerPhp.getInstance().creat(ApiService.class)
                .checkTask(requestBody)
                .compose(RxjavaHelper.observeOnMainThread())
                .subscribe(new BaseRxSubscribe<BaseResponse<String>>() {
                    @Override
                    public void onSuccess(BaseResponse<String> baseResponse) {
                        dismissCommonSubmitDialog();
                        getPublishDetail();
                    }

                    @Override
                    public void onError(ErrorMessage error) {
                        setErrorMessage(error);
                    }
                });
    }

    /**
     * no pass dialog
     */
    private void noPassDialog() {
        new WrapperDialog(this) {
            @Override
            public int getLayoutRes() {
                return R.layout.dialog_no_pass;
            }

            @Override
            protected void setDialogParams(Dialog dialog) {
                setDialogParams(dialog, DensityUtils.dp2px(290), WindowManager.LayoutParams.WRAP_CONTENT, Gravity.CENTER);
            }

            @Override
            public void help(ViewHelper helper) {
                helper.setOnClickListener(view -> {
                    switch (view.getId()) {
                        case R.id.btn_confirm:
                            EditText etReason = helper.getView(R.id.et_reason);
                            String reason = etReason.getText().toString().trim();
                            if (TextUtils.isEmpty(reason)) {
                                showToast("请输入驳回原因");
                                return;
                            }
                            checkTask(reason);
                            break;
                        case R.id.btn_cancel:
                            dismiss();
                            break;
                    }
                }, R.id.btn_confirm, R.id.btn_cancel);

            }
        }.show();
    }
}
